package com.foreknow.dao.impl;

import com.foreknow.bean.Admin;
import com.foreknow.dao.AdminDao;
import com.foreknow.db.DBManager;
import com.foreknow.db.JdbcTemplate;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AdminDaoImpl extends BaseDao implements AdminDao {
  @Override
  public boolean save(Admin admin) throws SQLException{
    String sql = "insert into admin(username,password,age,school) values(?,?,?,?)";
    int x = jdbcTemplate.update(sql,admin.getUsername(),admin.getPassword(),admin.getAge(),admin.getSchool());
    return x == 1;
  }


  @Override
  public Admin queryById(Integer id) throws SQLException{
    String sql = "select * from admin where id=?";
    EntityMapping mapping = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
    List<Object> list = jdbcTemplate.query(sql,mapping,id);
    Admin admin = null;
    if(list.size()>0){
       admin = (Admin)list.get(0);
    }
    return admin;
  }

  @Override
  public boolean update(Admin admin) throws SQLException{
    String sql = "update admin set username=?,password=?,age=?,school=? where id=?";
    int isRight = jdbcTemplate.update(sql,admin.getUsername(),admin.getPassword(),admin.getAge(),admin.getSchool(),admin.getId());
    return isRight==1;
  }

  @Override
  public boolean delete(Integer id) throws SQLException{
    String sql = "delete from admin where id=?";
    int isRight = jdbcTemplate.update(sql,id);
    return isRight==1;
  }

  @Override
  public List<Object> getQueryAll() throws SQLException{
    String sql = "select * from admin";
    EntityMapping mapping = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
    List<Object> list =  jdbcTemplate.query(sql,mapping);
    return list;
  }

  @Override
  public Admin isCheckLogin(String username, String password) throws SQLException {
    String sql = "select * from admin where username=? and password=?";
    EntityMapping mapping = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
    List<Object> list = jdbcTemplate.query(sql,mapping,username,password);
    if(list.size()>0){
      return (Admin) list.get(0);
    }
    return null;
  }


}
